<?php
class User_card_model extends CI_Model {

	function __construct()
    {
        parent::__construct();
    }
    /**
	 * 获取点卡信息
	 * @param int $id
	 */
	public function find_by_id($id) {
		$this->db->where('id', $id);
		return $this->db->get('user_card')->row_array();
	}
	/**
	 * 新增一张点卡，code随机
	 */
	public function add($user_id, $card_id) {
	  	$data = array('created' => date("Y-m-d H:i:s"), 'user_id' => $user_id, 'card_id' => $card_id);
		$this->db->insert("user_card", $data);
		return $this->db->insert_id();
	}
	
	public function find_cards($user_id, $is_used = null, $limit = null) {
		$sql = "select * from user_card where user_id=" . intval($user_id);
		if (!empty($is_used)) {
			$sql .= " and is_used=" . $is_used;
		}
		if (!empty($limit)) {
			$sql .= " limit ". $limit;
		}
		return $this->db->query($sql)->result_array();
	}
	
	public function get_cards_count($user_id, $is_used = null) {
		$sql = "select count(distinct(card_id)) as total from user_card where is_used=0 and user_id=" . intval($user_id);
		if (!empty($is_used)) {
			$sql .= " and is_used=" . $is_used;
		}
		$result = $this->db->query($sql)->row_array();
		return $result['total'];
	}
	public function set_as_used($user_id, $card_id) {
		$sql = "update  user_card set is_used = 1 , used_time=" . $this->db->escape(date("Y-m-d H:i:s")) . " where card_id = " . intval($card_id) ." and user_id=" . intval($user_id);
		return $this->db->query($sql);
	}
	
	public function transfer_card($from_user_id, $to_user_id, $count) {
		$sql = "update  user_card set user_id= " . intval($to_user_id) . " where user_id = " . intval($from_user_id) ." and is_used=0 limit " . $count;
		return $this->db->query($sql);
	}
}